﻿using FFMpegConv;

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace FileConvert
{
    public class MP4Convert : IConvert
    {
        public MP4Convert(string fromFile, string toFile)
        {
            _formFile = fromFile;
            _toFile = toFile;
            _ext = System.IO.Path.GetExtension(fromFile);
        }
        private string _formFile = "";
        private string _toFile = "";
        string _ext = "";
        public string SupportFormat
        {
            get
            {
                return ".avi;.wmv;.mp4;.flv;.mpg;.mov;.rm;.rmvb";
            }
        }

        public bool Convert()
        {
            bool result = false;

            string cmd = "";
            switch (_ext)
            {
                case ".avi":
                case ".flv":
                case ".mpg":
                case ".mov":
                case ".rmvb":
                case ".rm":
                case ".wmv":
                    cmd = string.Format(BlueCmd.GetCmd(BlueOptions.TVHighDefPALMP4), _formFile, _toFile);
                    break;
                case ".mp4":
                    //检查是否是h264编码,如果不是进行转换
                    var isH264Mp4 = VideoConvert.IsH264Mp4(_formFile);
                    if (isH264Mp4 == true)
                    {
                        cmd = "1";
                    }
                    else
                    {
                        cmd = string.Format(BlueCmd.GetCmd(BlueOptions.TVHighDefPALMP4), _formFile, _toFile);
                    }
                    break;
                //case ".wmv":
                //    //先转换成avi
                //    string newToFile = _toFile.ToLower().Replace(".mp4", ".avi");
                //    string mencoderCmd = string.Format("-noodml \"{0}\" -of avi -o \"{1}\" -ofps 20 -vf-add scale=224:176 -vf-add expand=224:176:-1:-1:1,rotate=2,flip -srate 44100 -ovc xvid -xvidencopts bitrate=350:max_bframes=0:quant_type=h263:me_quality=4 -oac lavc -lavcopts acodec=mp2:abitrate=96"
                //        , _formFile, newToFile);
                //    string mencodeExe = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tools", "mencoder.exe");
                //    string execCmd = string.Format("{0} {1}", mencodeExe, mencoderCmd);
                //    if (VideoConvert.Convert(mencodeExe, mencoderCmd) == true)
                //    {
                //        if (File.Exists(newToFile))
                //        {
                //            _formFile = newToFile;
                //        }
                //        cmd = string.Format(BlueCmd.GetCmd(BlueOptions.TVHighDefPALMP4), _formFile, _toFile);
                //    }
                //    else
                //    {
                //        cmd = string.Format(BlueCmd.GetCmd(BlueOptions.TVHighDefPALMP4), _formFile, _toFile);
                //    }
                //    break;
            }
            if (!string.IsNullOrEmpty(cmd))
            {
                Console.Clear();
                var section = AppConfig.configuration.GetSection("VideoConvertTools");
                //Console.WriteLine(section.GetSection("ffmpeg").Value);
                string command = section.GetSection("ffmpeg").Value;
                if (cmd == "1")
                {
                    System.IO.File.Copy(_formFile, _toFile);
                    result = true;
                }
                else
                {
                    result = VideoConvert.Convert(command,cmd);
                }
                }
            return result;
        }
       

    }

    public class VideoConvert
    {
        public static bool Convert(string exe,string cmd)
        {
           
            ProcessStartInfo psiProcInfo = new ProcessStartInfo();
            Process prcFFMPEG = new Process();
            try
            {
                psiProcInfo.FileName = exe;
                psiProcInfo.Arguments = cmd;
                psiProcInfo.UseShellExecute = true;
                psiProcInfo.WindowStyle = ProcessWindowStyle.Hidden;
                //psiProcInfo.RedirectStandardError = false;
                //psiProcInfo.RedirectStandardOutput = false;
                psiProcInfo.CreateNoWindow = false;
                psiProcInfo.WindowStyle = ProcessWindowStyle.Hidden;
               // prcFFMPEG.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler((object sender, System.Diagnostics.DataReceivedEventArgs e) => { });
                //prcFFMPEG.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler((object sender, System.Diagnostics.DataReceivedEventArgs e) => { });
                prcFFMPEG.StartInfo = psiProcInfo;
                if (prcFFMPEG.Start())
                {
                   // prcFFMPEG.BeginErrorReadLine(); //开始异步读取
                    prcFFMPEG.WaitForExit();//等待完成
                    prcFFMPEG.Close(); //关闭进程
                    prcFFMPEG.Dispose(); //释放资源
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {

                return false;
            }
        }

        public static bool IsH264Mp4(string inputFileName)
        {

            string ext = System.IO.Path.GetExtension(inputFileName);
            if (ext.ToLower() != ".mp4")
            {
                return false;
            }
            else
            {
               string result = "";
                var section = AppConfig.configuration.GetSection("VideoConvertTools");
                string command = section.GetSection("ffmpeg").Value;
                result = RunProcess(command, $"-i {inputFileName}");
                int post = result.IndexOf("Video: h264");
                if (post > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }


        public static string RunProcess(string cmd, string param)
        {

            //create a process info
            ProcessStartInfo oInfo = new ProcessStartInfo(cmd, param);
            oInfo.UseShellExecute = false;
            oInfo.CreateNoWindow = true;
            oInfo.RedirectStandardOutput = true;
            oInfo.RedirectStandardError = true;

            string output = null;
            StreamReader srOutput = null;

            //try the process
            try
            {
                //run the process
                Process proc = System.Diagnostics.Process.Start(oInfo);

                srOutput = proc.StandardError;//true; 必须放在WaitForExit()前面
                output = srOutput.ReadToEnd();//true; 必须放在WaitForExit()前面
                proc.WaitForExit();
                proc.Close();
            }
            catch (Exception)
            {
                output = string.Empty;
            }
            finally
            {
                if (srOutput != null)
                {
                    srOutput.Close();
                    srOutput.Dispose();
                }
            }
            return output;
        }
    }
}

